﻿using BaiTu.EventEntity;
using BaiTu.IQueueService;
using BaiTu.QueueEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BaiTu.EventServices
{
    /// <summary>
    /// 处理事件接收队列中的消息，触发相应事件处理Handler的执行
    /// </summary>
    internal class EventQueueProcessor
    {
        private IQueue queueSrv = BaiTu.IOCServices.EngineContext.Current.Resolve<IQueue>();

        public void Process(object state)
        {

            while (true)
            {
                Message<BaiTu.EventEntity.EventInfo> msg = queueSrv.GetRequestFromClient<BaiTu.EventEntity.EventInfo>();

                BaiTu.EventEntity.EventInfo info = EventProcessorHandlerSearcher.Find(msg.Body.ProcessClassType);

                Type eventClassType = Type.GetType(info.SourceClassType);
                if (eventClassType == null)
                {
                    Assembly asmb = Assembly.LoadFrom(info.SourceAssemblyName);
                    eventClassType = asmb.GetType(info.SourceClassType);
                }
                if (eventClassType == null)
                {
                    continue;
                }

                Type eventHandlerProcessorType = Type.GetType(info.ProcessClassType);
                if (eventHandlerProcessorType == null)
                {
                    Assembly asmb = Assembly.LoadFrom(info.ProcessAssemblyName);
                    eventHandlerProcessorType = asmb.GetType(info.ProcessClassType);
                }
                if (eventHandlerProcessorType == null)
                {
                    continue;
                }
                System.Reflection.MethodInfo mi = eventHandlerProcessorType.GetMethod("Process");
                if (mi == null)
                    continue;

                object evtObj = Common.Helpers.XMLSerializationHelper.DeSerialize(msg.Body.Xml, eventClassType);

                object o = Activator.CreateInstance(eventHandlerProcessorType);
                mi.Invoke(o, new object[] { evtObj });
            }
        }
    }
}
